<?php

/**
 * finalClothQcTestForm actions.
 *
 * @package    WacStorehouse
 * @subpackage finalClothQcTestForm
 * @author     JianBinBi
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class finalClothQcTestFormActions extends WacCommonActions
{
  /*
   * @return list data array
   */
  public function executeGetFormData(sfWebRequest $request)
  {
      
      $resultSet = JsCommonData::getCommonDatum();
      $resultSet['info'] = JsCommonData::getSuccessDatum();

      // default data setting
//      $resultSet['items']['unit'] = Doctrine::getTable(WacTable::$unit)->getCodeNameHash();

      // editing data setting
      if($request->hasParameter("id") && $request->getParameter("id")!="0")
      {
          $objForm = Doctrine::getTable(WacTable::$finalClothQcTestForm)->findOneBy("id", $request->getParameter("id"));
          $resultSet['items']['stock_goods_items'] = $objForm->getWacDispatchOrder()->getSubItemsWithDetail(array(), 1, 10);
          $resultSet['items']['target_items'] = $objForm->getSubItemsWithDetail();
      }
      else{
          $resultSet['items']['stock_goods_items'] = array();
          $resultSet['items']['target_items'] = array();
      }

//      $resultSet['items']['default']['currency_code_name'] = Doctrine::getTable(WacTable::$systemParameter)->getValueByCode(WacAppSettingCode::$currency);
      $resultSet['items']['default']['unit_code'] = Doctrine::getTable(WacTable::$systemParameter)->getValueByCode(WacAppSettingCode::$clothUnitCode);

      return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);

  }

  public function executeGetList(sfWebRequest $request)
  {
      $jqGridDataHelper = JqGridDataHelper::getInstance();

        $arrParams = array();
        if($jqGridDataHelper->loadComplexQuery($request)) {

            if($request->hasParameter(JqGridDataHelper::$KEY_SEARCH_FIELD) && $request->getParameter(JqGridDataHelper::$KEY_SEARCH_OPER)!="") {
                $arrParams['andWhere'] = array(
                        $jqGridDataHelper->getCondMapStr($request->getParameter(JqGridDataHelper::$KEY_SEARCH_OPER), "t1.".$request->getParameter(JqGridDataHelper::$KEY_SEARCH_FIELD), $request->getParameter(JqGridDataHelper::$KEY_SEARCH_STRING))
                );
            }

            if($request->hasParameter("status")) {
                $arrParams['andWhere'][] = "t1.status=".StaticWacFormStatus::getId($this->getRequest()->getParameter("status"));
            }

            if($request->hasParameter(JqGridDataHelper::$KEY_SIDX)) {
                switch($request->getParameter(JqGridDataHelper::$KEY_SIDX)) {
                    case "production_order_code":
                        $arrParams['orderBy'] = "wpo.code ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    case "target_name":
                        $arrParams['orderBy'] = "wt.name ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    case "status_name":
                        $arrParams['orderBy'] = "t1.status ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    case "maker_name":
                        $arrParams['orderBy'] = "wm.username ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    case "auditor_name":
                        $arrParams['orderBy'] = "wa.username ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    default:
                        $arrParams['orderBy'] = "t1.".$request->getParameter(JqGridDataHelper::$KEY_SIDX)." ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                }
            }

            $resultSet = $this->mainModuleTable->getCustomList($arrParams, $request->getParameter(JqGridDataHelper::$KEY_PAGE), $request->getParameter(JqGridDataHelper::$KEY_ROWS), false);
        }
        else {
            if($request->hasParameter("status")) {
                $arrParams['andWhere'][] = "status=".StaticWacFormStatus::getId($this->getRequest()->getParameter("status"));
            }
            
            $resultSet = $this->mainModuleTable->getCommonList($request->getParameter(JqGridDataHelper::$KEY_PAGE), $request->getParameter(JqGridDataHelper::$KEY_ROWS), false, $arrParams);
        }

        $filterResultSet = $this->filterList($resultSet);

        $pager = $this->mainModuleTable->getPager();
        $filterResultSet = $jqGridDataHelper->convert($filterResultSet, $pager, JsCommonData::getSuccessDatum());

        return OutputHelper::getInstance()->outputJsonOrTextFormat($filterResultSet, $this);
      
  }

  /*
   * override filter list
   */
  public function filterList($listObjs)
  {
      $filterArr = array();
      if(count($listObjs) > 0)
      {
          foreach($listObjs as $listObj)
          {
              $tmpArr = $listObj->toArray();
              $tmpArr['production_order_code']        = $listObj->getWacProductionOrder()->getCode();
              $tmpArr['dispatch_order_code']        = $listObj->getWacDispatchOrder()->getCode();
              $tmpArr['target_name']                  = $listObj->getWacTarget()->getName();

              $formatDate = new DateTime($listObj->getGoodsReturnDate());
              $tmpArr['goods_return_date']            = $formatDate->format("Y-m-d");

              $formatDate = new DateTime($listObj->getDispatchDate());
              $tmpArr['dispatch_date']                = $formatDate->format("Y-m-d");

              $formatDate = new DateTime($listObj->getQcDate());
              $tmpArr['qc_date']                      = $formatDate->format("Y-m-d");

              $tmpArr['maker_name']                   = $listObj->getWacMaker()->getUsername();

              $tmpArr['status_name']                  = StaticWacFormStatus::getCaptionById($listObj->getStatus());

              $filterArr[] = $tmpArr;
          }
      }

      return $filterArr;
  }

  /*
   * @return inspect result
   */
  public function inspectDataValidation(sfWebRequest $request, $params=array())
  {
      $result    = JsCommonData::getSuccessDatum();
      $reqParams = $request->getParameterHolder()->getAll();


      $exceptId = isset($reqParams['id']) ? $reqParams['id'] : 0;
      if($this->mainModuleTable->isExistedCode($reqParams['code'], $exceptId))
      {
         $result = JsCommonData::getErrorDatum(WacErrorCode::getInfo(WacErrorCode::$duplicatedName, $reqParams['code']), WacErrorCode::$duplicatedName);
         return $result;
      }

      if(empty($reqParams['dispatch_order_id']) || !Doctrine::getTable(WacTable::$dispatchOrder)->isExistedId($reqParams['dispatch_order_id'])){
         $result = JsCommonData::getErrorDatum(
                        Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_invalid_dispatch_order"),  WacErrorCode::$logicError
                  );
         return $result;
      }

      if($exceptId==0){
          $objDispatchOrder = Doctrine::getTable(WacTable::$dispatchOrder)->findOneBy('id', $reqParams['dispatch_order_id']);
          if($objDispatchOrder->getWacFinalClothQcTestHistory()->count()>0){
              $result = JsCommonData::getErrorDatum(
                            Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_dispatch_order_qc_only_once"),  WacErrorCode::$logicError
                      );
             return $result;
          }          
      }

      if(empty($reqParams['target_id']) || !Doctrine::getTable(WacTable::$factory)->isExistedId($reqParams['target_id'])){
         $result = JsCommonData::getErrorDatum(
                        Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_invaild_target"),  WacErrorCode::$logicError
                  );
         return $result;
      }

      return $result;
  }

    /*
   * @return list data array
   */
  public function executeAdd(sfWebRequest $request)
  {
      $reqParams     = $this->getRequest()->getParameterHolder()->getAll();
      $resultSet     = JsCommonData::getCommonDatum();
      $inspectResult = $this->inspectDataValidation($request);

      if($inspectResult['status'] == WacOperationStatus::$Error)
      {
          $resultSet['info'] = $inspectResult;
      }
      else
      {
          $objDispatchOrder = Doctrine::getTable(WacTable::$dispatchOrder)->findOneBy('id', $reqParams['dispatch_order_id']);
          $objProductionOrder = $objDispatchOrder->getWacProductionOrder();
          $targetItem        = $this->mainModuleTable->create();

          if(count($reqParams)>0) {
              $targetItem->setMakerId($this->getUser()->getGuardUser()->getId());
              $targetItem->setDispatchOrderId($objDispatchOrder->getId());
              $targetItem->setProductionOrderId($objProductionOrder->getId());
              $targetItem->setSrcProductionOrderId($objProductionOrder->getId());
              if(isset($reqParams['code']))                {$targetItem->setCode($reqParams['code']);}
              if(isset($reqParams['target_id']))           {$targetItem->setTargetId($reqParams['target_id']);}
              if(isset($reqParams['qc_date']))             {$targetItem->setQcDate($reqParams['qc_date']);}
              if(isset($reqParams['dispatch_date']))       {$targetItem->setDispatchDate($reqParams['dispatch_date']);}
              if(isset($reqParams['goods_return_date']))   {$targetItem->setGoodsReturnDate($reqParams['goods_return_date']);}
              if(isset($reqParams['memo']))                {$targetItem->setMemo($reqParams['memo']);}

              $targetItem->setStatus(StaticWacFormStatus::getId(StaticWacFormStatus::$init));
              $targetItem->save();

              $params = array(
                  "dispatch_order_id" => $objDispatchOrder->getId(),
                  "qc_form_id" => $targetItem->getId(),
              );
              $objFinalClothQcTestHistory = Doctrine::getTable(WacTable::$finalClothQcTestHistory)->createByParams($params);

              if(count($reqParams['qc_items'])>0)
              {
                  foreach($reqParams['qc_items'] as $k=>$item)
                  {
                      $goodsId = substr($k, 3);
//                      $objSrcDispatchOrderItem = Doctrine::getTable(WacTable::$dispatchOrderItem)->findOneByOrderAndGoods($objDispatchOrder, $goodsId);
                      Doctrine::getTable(WacTable::$finalClothQcTestFormItem)->createFromDispatchOrderItem($targetItem->getId(), $item['dispatch_order_item_id'], $item);
                      
                  }
              }

              $this->afterAdd($request, $targetItem);

              // process production order
              $objWorkflowItem = Doctrine::getTable(WacTable::$workflowItem)->findOneBy('code', StaticWacWorkFlow::$wfQcFinalCloth);
              $objProductionOrder->setCurrentWorkflowItemId($objWorkflowItem->getId());
              $objProductionOrder->save();
          }

          $resultSet['items'][0] = $targetItem->toArray();
          $resultSet['info']     = JsCommonData::getSuccessDatum(
                                       Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_add_succ")
                                   );
      }

      return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);

  }

  /*
   * @return list data array
   */
  public function executeEdit(sfWebRequest $request)
  {
      // forward to 404 if no id
      $this->forward404Unless($request->hasParameter('id'));

      $reqParams     = $this->getRequest()->getParameterHolder()->getAll();
      $resultSet     = JsCommonData::getCommonDatum();
      $inspectResult = $this->inspectDataValidation($request);

      if($inspectResult['status'] == WacOperationStatus::$Error)
      {
          $resultSet['info'] = $inspectResult;
      }
      else
      {
          $targetItem = $this->mainModuleTable->findOneById($request->getParameter('id'));
          $objDispatchOrder = Doctrine::getTable(WacTable::$dispatchOrder)->findOneBy('id', $reqParams['dispatch_order_id']);
          $objProductionOrder = $objDispatchOrder->getWacProductionOrder();

          if(count($reqParams)>0) {
              if($targetItem->getDispatchOrderId()!= $reqParams['dispatch_order_id']){
                  
//                  $targetItem->deleteSubItems();
                  $targetItem->getWacSubItems()->delete();
                  $objQcHistory = Doctrine::getTable(WacTable::$finalClothQcTestHistory)->findOneByAssocateForm($targetItem->getWacDispatchOrder(), $targetItem);
                  if($objQcHistory){
                      $objQcHistory->setDispatchOrderId($reqParams['dispatch_order_id']);
                      $objQcHistory->save();
                  }
              }

              if(count($reqParams['qc_items'])>0)
              {
                  $goodsIds =  array();
                  foreach($reqParams['qc_items'] as $k=>$item)
                  {
                      $goodsId = substr($k, 3);
                      $goodsIds[] = $goodsId;
                      $objSubItem = Doctrine::getTable(WacTable::$finalClothQcTestFormItem)->findOneByFormAndGoods($targetItem->getId(), $goodsId);
                      if($objSubItem) {  // existed dispatchOrderItem
                          Doctrine::getTable(WacTable::$finalClothQcTestFormItem)->createFromDispatchOrderItem($targetItem->getId(), $item['dispatch_order_item_id'], $item, $objSubItem);
                      }
                      else {
                          $objSrcDispatchOrderItem = Doctrine::getTable(WacTable::$dispatchOrderItem)->findOneByOrderAndGoods($objDispatchOrder, $goodsId);
                          Doctrine::getTable(WacTable::$finalClothQcTestFormItem)->createFromDispatchOrderItem($targetItem->getId(), $item['dispatch_order_item_id'], $item);
                      }
                  }

                  $objSubItems = $targetItem->getWacSubItems();
                  if($objSubItems->count()>0)
                  {
                      foreach($objSubItems as $objSubItem)
                      {
                          if(!in_array($objSubItem->getGoodsId(), $goodsIds))
                          {
                              $objSubItem->delete();
                          }
                      }
                  }
              }

              $targetItem->setMakerId($this->getUser()->getGuardUser()->getId());
              $targetItem->setDispatchOrderId($objDispatchOrder->getId());
              $targetItem->setProductionOrderId($objProductionOrder->getId());
              $targetItem->setSrcProductionOrderId($objProductionOrder->getId());
              if(isset($reqParams['code']))                {$targetItem->setCode($reqParams['code']);}
              if(isset($reqParams['target_id']))           {$targetItem->setTargetId($reqParams['target_id']);}
              if(isset($reqParams['qc_date']))             {$targetItem->setQcDate($reqParams['qc_date']);}
              if(isset($reqParams['dispatch_date']))       {$targetItem->setDispatchDate($reqParams['dispatch_date']);}
              if(isset($reqParams['goods_return_date']))   {$targetItem->setGoodsReturnDate($reqParams['goods_return_date']);}
              if(isset($reqParams['memo']))                {$targetItem->setMemo($reqParams['memo']);}

              $targetItem->setStatus(StaticWacFormStatus::getId(StaticWacFormStatus::$init));

              $targetItem->save();

              $this->afterEdit($request, $targetItem);
          }

          $resultSet['items'][0] = $targetItem->toArray();
          $resultSet['info']     = JsCommonData::getSuccessDatum(
                                       Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_edit_succ")
                                   );
      }

      return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);

  }

  /*
   * @return inspect result
  */
  protected function auditValidation(sfWebRequest $request, $objQcForm, $params=array()) {
      $result    = JsCommonData::getSuccessDatum();
      $reqParams = $request->getParameterHolder()->getAll();

      if($objQcForm->getStatus() != StaticWacFormStatus::getId(StaticWacFormStatus::$init)) {
          $result = JsCommonData::getErrorDatum(
                  Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_invaild_audit_status"),  WacErrorCode::$logicError
          );
          return $result;
      }

      $items = $objQcForm->getWacSubItems();
      if($items->count()==0) {
          $result = JsCommonData::getErrorDatum(
                  Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_invaild_audit_zero_item"),  WacErrorCode::$logicError
          );
          return $result;

      }

      return $result;
  }

  /*
     * @return list data array
  */
  public function executeAudit(sfWebRequest $request) {
      // forward to 404 if no id
      $this->forward404Unless($request->hasParameter('form_id'));

      $resultSet = JsCommonData::getCommonDatum();

      $objQcForm = Doctrine::getTable(WacTable::$finalClothQcTestForm)->findOneBy('id', $request->getParameter('form_id'));
      $validationResult = $this->auditValidation($request, $objQcForm);

      if($validationResult['status'] == WacOperationStatus::$Error) {
          $resultSet['info'] = $validationResult;
      }
      else {
          try {
              $objQcFactory = $objQcForm->getWacDispatchOrder()->getWacTarget();
              $opOkResultData = $objQcFactory->getQcMinusOrderItemConsumeGoods($objQcForm->getWacSubItems(), WacQualityCode::$ok);
              $opNokResultData = $objQcFactory->getQcMinusOrderItemConsumeGoods($objQcForm->getWacSubItems(), WacQualityCode::$nok);
              if($opOkResultData["error"]) {
                  $errorMsgPtn = Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_goods_number_insufficient_in_factory");
                  $errorMsg = MessageHelper::getInstance()->getMsgOfMinusOrderItemConsumeGoods($opOkResultData, $errorMsgPtn);
                  throw new WacAppException($errorMsg, WacErrorCode::$logicError);
              }
              elseif($opNokResultData["error"]) {
                  $errorMsgPtn = Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_goods_number_insufficient_in_factory");
                  $errorMsg = MessageHelper::getInstance()->getMsgOfMinusOrderItemConsumeGoods($opNokResultData, $errorMsgPtn);
                  throw new WacAppException($errorMsg, WacErrorCode::$logicError);
              }
              else {
                  $objQcFactory->decreaseFinalClothQcTestFormGoods($objQcForm, WacQualityCode::$ok);
                  $objQcFactory->decreaseFinalClothQcTestFormGoods($objQcForm, WacQualityCode::$nok);
              }

              $objSupplier = $objQcForm->getWacDispatchOrder()->getWacSupplier();
              $objSupplier->storeQcGoods($objQcForm, WacQualityCode::$nok);
              $objTarget = $objQcForm->getWacTarget();
              $objTarget->storeQcGoods($objQcForm, WacQualityCode::$ok);
              
              $objQcForm->setStatus(StaticWacFormStatus::getId(StaticWacFormStatus::$audited));
              $objQcForm->setAuditorId($this->getUser()->getGuardUser()->getId());
              $objQcForm->setAuditorDate(format_date(time()));
              $objQcForm->save();

              $resultSet['info'] = JsCommonData::getSuccessDatum(
                      Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_audit_succ")
              );

              $this->afterAudit($request, $objQcForm);
          }
          catch (WacAppException $e) {		// catch application exception, and handle it
              $resultSet['info'] = JsCommonData::getErrorDatum($e->getMessage());
          }
          catch (Exception $e) {        // catch general exception
              WacAppException::handleGeneralError($e);
          }

      }

      return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);
  }

}
